<?php

include_once '_params.php';

function fetch_data($data, $step = 1) {
  $tags = get_param('flowTags');
  if ($step != 1) {
    $data = cumulate_data($data, $step);
  }
  return group_data($tags, $data);
}

function group_data($tags, $data) {
  $output = [];
  $plain = [];
  foreach ($data as $line) {
    $moment = $line['moment'];
    $tiny = [];
    $cell = [
      // 'moment' => $moment,
      'summary' => ['DEP' => 0, 'ARR' => 0, 'ALL' => 0],
      'airports' => [],
    ];
    foreach ($line['content'] as $index => $value) {
      $tag = $tags[$index];
      $tiny[] = [
        // 't' => $moment,
        'k' => $tag,
        'v' => $value,
      ];
      $tag_arr = explode('_', $tag);
      $airport = $tag;
      $type = $tag;
      $point = $tag;
      if (count($tag_arr) == 3) {
        $airport = $tag_arr[0];
        $type = $tag_arr[1];
        $point = $tag_arr[2];
      }
      $plain[] = [
        'moment' => $moment,
        'airport' => $airport,
        'type' => $type,
        'value' => $value,
      ];
      // each type of total
      $cell['summary']['ALL'] += $value;
      if (!isset($cell['summary'][$type])) {
        $cell['summary'][$type] = $value;
      } else {
        $cell['summary'][$type] += $value;
      }
      // each airport
      if (!isset($cell['airports'][$airport])) {
        // $cell['airports'][$airport] = ['total' => ['ALL' => $value], 'types' => []];
        $cell['airports'][$airport] = ['total' => $value, 'types' => []];
      } else {
        // $cell['airports'][$airport]['total']['ALL'] += $value;
        $cell['airports'][$airport]['total'] += $value;
      }
      // each airport/type & airport/total
      if (!isset($cell['airports'][$airport]['types'][$type])) {
        // $cell['airports'][$airport]['total'][$type] = $value;
        $cell['airports'][$airport]['types'][$type] = ['total' => $value, 'points' => []];
      } else {
        // $cell['airports'][$airport]['total'][$type] += $value;
        $cell['airports'][$airport]['types'][$type]['total'] += $value;
      }
      // each airport/type/points
      $cell['airports'][$airport]['types'][$type]['points'][$point] = $value;
    }
    $output[] = [
      'moment' => $moment,
      'tiny' => $tiny,
      'cell' => $cell,
    ];
  }
  return $output;
}

function cumulate_data($data, $step) {
  $output = [];
  for ($i = 0; $i < count($data); $i += $step) {
    $content = [];
    for ($j = 0; $j < $step; $j++) {
      foreach ($data[$i + $j]['content'] as $index => $value) {
        // echo $index . '=>' . $value . PHP_EOL;
        $content[$index] = (isset($content[$index]) ? $content[$index] : 0) + $value;
      }
    }
    $output[] = [
      'moment' => $data[$i]['moment'],
      'content' => $content,
    ];
  }
  return $output;
}